<template>
  <div class="app-container bg-gray">
    <el-card class="box-1">
      <el-row :gutter="20" class="model">
        <el-col :xs="8" :sm="8" :md="7" :lg="6" :xl="4">
          <el-card shadow="hover">
            <span>历史余额总和</span>
            <div><span>￥ </span> {{ info['totalMoney'] }}</div>
          </el-card>
        </el-col>
        <el-col :xs="8" :sm="8" :md="7" :lg="6" :xl="4">
          <el-card shadow="hover">
            <span>钱包余额</span>
            <div><span>￥ </span> {{ info['bonus'] }}</div>
          </el-card>
        </el-col>
        <el-col :xs="8" :sm="8" :md="7" :lg="6" :xl="4">
          <el-card shadow="hover">
            <span>已提现余额</span>
            <div><span>￥ </span> {{ info['withdrawMoney'] }}</div>
          </el-card>
        </el-col>
      </el-row>
      <el-row class="model">
        <el-button v-if="queryMatch(130)" type="danger" icon="el-icon-upload2" @click="takeCashDialogVisible=true">余额提现</el-button>
        <el-button v-if="searchTerms.id&&queryMatch(187)" type="danger" style="margin-right: 15px;" @click="showDialog">余额修改</el-button>
        <el-select v-if="$store.getters.id===1" v-model="searchTerms.id" placeholder="工作人员" class="select" filterable clearable @change="getData">
          <el-option-group
            v-for="group in allMemberList"
            :key="group.label"
            :label="group.label">
            <el-option
              v-for="item in group['personnel']"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-option-group>
        </el-select>
        <el-select v-model="searchTerms.type" placeholder="明细类型" class="select" clearable @change="getData">
          <el-option :value="1" label="入账明细" />
          <el-option :value="2" label="提现明细" />
        </el-select>
        <el-date-picker
          v-model="searchTerms.date"
          :editable="false"
          class="picker"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          @change="getData"/>
      </el-row>
      <el-table v-loading="tableLoading" :data="tableData" :max-height="tableMaxHeight" border highlight-current-row @sort-change="handleSortChange">
        <el-table-column prop="id" label="ID" min-width="70" header-align="center" align="center" sortable />
        <el-table-column v-if="th[0].check" prop="member_name" label="客户名称" min-width="120" header-align="center" align="center">
          <template slot-scope="scope">
            {{ scope.row['member_name'] || '--' }}
          </template>
        </el-table-column>
        <el-table-column v-if="th[1].check" prop="member_phone" label="手机" min-width="120" header-align="center" align="center" sortable>
          <template slot-scope="scope">
            {{ scope.row['member_phone'] || '--' }}
          </template>
        </el-table-column>
        <el-table-column v-if="th[2].check" prop="money" label="金额" min-width="110" header-align="center" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.money.indexOf('-')===0?'danger':'success'">{{ scope.row.money }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="number_sn" label="业绩订单号" min-width="160" header-align="center" align="center">
          <template slot-scope="scope">
            <router-link v-if="scope.row.ach_id" :to="`/orders/achievement/info?id=${scope.row.ach_id}`">{{ scope.row['number_sn'] || '--' }}</router-link>
            <span v-else>{{ scope.row['number_sn'] || '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="th[3].check" prop="goods_money" label="订单金额" min-width="110" header-align="center" align="center">
          <template slot-scope="scope">
            {{ scope.row['goods_money'] || '--' }}
          </template>
        </el-table-column>
        <el-table-column v-if="th[4].check" label="操作记录" min-width="300" header-align="center" align="center">
          <template slot-scope="scope">
            {{ scope.row['type']===0?'售前提成'
            :scope.row['type']===1?'售后提成'
            :scope.row['type']===2?'余额提现'
            :scope.row['type']===3?'售前退款'
            :scope.row['type']===4?'奖金'
            :scope.row['type']===5?'奖金提现'
            :scope.row['type']===6?'增加余额'
            :scope.row['type']===7?'减少余额'
            :scope.row['type']===8?'增加奖金':'减少奖金' }}
            {{ (scope.row['goods_name']?(',商品名称'+ scope.row['goods_name']):'')+(scope.row['order_number']?(', 订单号: '+scope.row['order_number']):'') }}
          </template>
        </el-table-column>
        <el-table-column v-if="th[5].check" prop="remarks" label="备注" min-width="160">
          <template slot-scope="scope">
            {{ scope.row['remarks']?scope.row['remarks']:'--' }}
          </template>
        </el-table-column>
        <el-table-column label="操作人" min-width="120" header-align="center" align="center">
          <template slot-scope="scope">
            {{ scope.row['submitter']||'--' }}
          </template>
        </el-table-column>
        <el-table-column label="审核人" min-width="120" header-align="center" align="center">
          <template slot-scope="scope">
            {{ scope.row['auditor']||'--' }}
          </template>
        </el-table-column>
        <el-table-column v-if="th[6].check" prop="created_at" label="发放时间" min-width="160" header-align="center" align="center" sortable/>
      </el-table>
      <el-pagination
        :current-page.sync="currentPage"
        :page-size="pageSize"
        :page-sizes="pageSizes"
        :total="total"
        class="pagination"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"/>
    </el-card>

    <!--余额修改弹窗-->
    <el-dialog :visible.sync="dialogVisible" title="余额修改" width="480px" class="dialog" center @close="resetDialog('form')">
      <el-form ref="form" :model="form" :rules="formRules" label-width="90px">
        <el-form-item label="类型">
          <el-radio-group v-model="form.type" prop="type">
            <el-radio :label="0">账户余额</el-radio>
            <el-radio :label="1">奖金余额</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="操作">
          <el-radio-group v-model="form.doType" prop="doType">
            <el-radio :label="1">增加</el-radio>
            <el-radio :label="0">减少</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="金额" prop="money">
          <el-input-number v-model="form.money" :min="0" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" rows="3"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="takeCashDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitDialog('form')">确 定</el-button>
      </div>
    </el-dialog>

    <!--提现弹窗-->
    <el-dialog :visible.sync="takeCashDialogVisible" title="余额提现" width="480px" class="dialog" center @close="resetTakeCashDialog('form')">
      <el-form ref="form2" :model="form2" :rules="formRules2" label-width="90px">
        <el-form-item label="金额" prop="money">
          <el-input v-model="form2.money" type="number" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form2.remarks" type="textarea" rows="3"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="takeCashDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitTakeCash('form2')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ColumnController } from '../components';
import { handleCurrentChange, handleSizeChange, handleSortChange, columnCheck } from '../../utils/table';
export default {
  components: { ColumnController },
  data() {
    return {
      downloadLoading: false,
      searchTerms: {
        searchValue: '',
        date: [],
        type: '',
        id: ''
      },

      allMemberList: [], // 所有人员列表

      info: {},

      // 表格相关数据
      tableMaxHeight: document.documentElement.clientHeight - 280,

      // 表格相关参数
      tableLoading: false,
      currentPage: 1,
      pageSize: this.$store.getters.userInfo.pageSize,
      pageSizes: [10, 20, 50, 100, 1000],
      total: 0,
      tableData: [],
      th: [{ name: '客户名称', check: true },
        { name: '手机', check: true },
        { name: '支付金额', check: true },
        { name: '余额', check: true },
        { name: '操作记录', check: true },
        { name: '备注', check: true },
        { name: '操作时间', check: true }],

      // 余额修改弹窗
      dialogVisible: false,
      form: {
        type: 0,
        doType: 1,
        money: 1,
        remarks: ''
      },
      formRules: {
        type: [{ required: true, message: '请选择操作的类型', trigger: 'change' }],
        doType: [{ required: true, message: '请选择增加或减少', trigger: 'change' }],
        money: [{ required: true, message: '请输入提现金额', trigger: 'change' }],
        remarks: [{ required: true, message: '请输入修改备注', trigger: 'change' }]
      },

      takeCashDialogVisible: false,
      form2: {
        type: 1,
        money: null,
        remark: ''
      },
      formRules2: {
        money: [{ required: true, message: '请输入提现金额', trigger: 'change' }]
      }
    }
  },
  watch: {},
  created() {
    this.searchTerms.id = this.$route.query.id || '';
    this.getData();
    this.getAllMemberList();
  },
  methods: {
    handleCurrentChange, handleSizeChange, handleSortChange, columnCheck,

    /**
     *  获取所有用户列表（包括离职人员）
     *  接口:'user/admin-list'
     */
    getAllMemberList() {
      const url = 'user/admin-list'
      this.$store.dispatch('GetConnect', { url }).then(res => {
        this.allMemberList = res.data.list
      }).catch(e => {
        this.$message.error(e.msg + ',请刷新或联系管理员')
      })
    },

    getData(order) {
      this.tableLoading = true;
      order || (order = {});
      const url = 'bonus/mywallet';
      const data = {
        page_no: this.currentPage,
        page_size: this.pageSize,
        search: this.searchTerms.searchValue,
        type: this.searchTerms.type,
        types: 1,
        id: this.searchTerms.id
      };
      this.searchTerms.date && this.searchTerms.date.length !== 0 && (data.start_time = this.searchTerms.date[0] + ' 00:00:00', data.end_time = this.searchTerms.date[1] + ' 23:59:59')
      order.sortName && (data.sortName = order.sortName);
      order.sortOrder && (data.sortOrder = order.sortOrder);
      this.$store.dispatch('GetConnect', { url, data }).then(res => {
        this.tableData = res.data.list.rows;
        this.info = {
          bonus: res.data['bonus'],
          withdrawMoney: res.data['withdrawMoney'],
          totalMoney: res.data['totalMoney']
        };
        this.total = res.data.list.total;
        this.tableLoading = false;

        let count1 = 0;
        for (let i = 0; i < this.tableData.length; i++) {
          count1 = count1 + Number(this.tableData[i]['money'])
        }
        console.log('======================');
        console.log(count1);
      }).catch(e => {
        this.tableLoading = false;
        this.$message.error(e.msg + ',请刷新或联系管理员');
      })
    },

    toDelete() {
      this.$confirm('此操作将删除该业绩订单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      });
    },

    showDialog(){
      this.dialogVisible = true;
    },

    /**
     * 修改选择客户的赠送金及资金
     */
    submitDialog(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const data = this.form;
          data.uid = this.searchTerms.id;
          const url = 'bonus/capitalOperation';
          this.$store.dispatch('GetConnect', { url, data }).then(res => {
            this.$message.success(res.msg);
            this.getData();
            this.dialogVisible = false;
          }).catch((err) => {
            this.$message.error(err.msg);
          })
        } else {
          this.$message.error('提交失败,请检查必填项');
        }
      })
    },

    resetDialog(formName) {
      this.$refs[formName].resetFields();
    },

    /**
     * 修改选择客户的赠送金及资金
     */
    submitTakeCash(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const data = this.form2;
          const url = 'bonus/applymoney';
          this.$store.dispatch('GetConnect', { url, data }).then(res => {
            this.$message.success(res.msg);
            this.getData();
            this.takeCashDialogVisible = false;
          }).catch((err) => {
            this.$message.error(err.msg);
          })
        } else {
          this.$message.error('提交失败,请检查必填项');
        }
      })
    },

    resetTakeCashDialog(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>

<style lang="scss" type="text/scss" scoped>
  @import '../../styles/index.scss';
  .box-1 {
    .model {
      display: flex;
      align-items: flex-end;
      margin-bottom: 15px;
      .el-select{
        margin-left: 10px;
      }
      .el-card {
        color: #fff;
        background-color: $panGreen;
        span {
          font-size: 14px;
        }
        div {
          font-size: 24px;
          margin-top: 10px;
        }
      }
    }
    .header {
      @include flex-row(center, space-between);
      flex-wrap: wrap;
      padding-bottom: 15px;
      div {
        @include flex-row(center, flex-start);
        flex-wrap: wrap;
        .do-btn {
          @extend .bg-green;
          margin-left: 6px;
        }
        .search-input {
          width: 240px;
        }
      }
    }
  }
  .select {
    padding-right: 15px;
    width: 180px;
  }
</style>

